#include "ListPanel.h"

ListPanel::ListPanel(MasterComponent* master, int w, int h) :
	BoundedPanel(w, h), SwitchablePanel(master) {
	model = new BoxModel(this, filteredItems);

	addAndMakeVisible(listBox = new ListPanelBox(this, T(""), model));
	addAndMakeVisible(search = new SearchField(this, String(T("Search:"))));
	//	addAndMakeVisible(searchWithin = new SearchField(this, String(T("Search Within Results:"))));
	addAndMakeVisible(backButton = new BackButton((SwitchablePanel*) this));

	backButton->setBounds(35, 35, 40, 40);
	listBox->setRowHeight(72);
	listBox->selectRow(0);
}

ListPanel::~ListPanel() {
	delete model;
	delete listBox;
	delete search;
	//	delete searchWithin;
	//	for (int i = 0; i < items.size(); i++) {
	//		delete items[i].getImage();
	//	}
}

void ListPanel::paintListBox(Graphics& g) {
	g.setColour(Colours::grey);
	g.drawRect(boxRect.expanded(1, 1));
}

void ListPanel::resized() {
	int topSpacer = 130;
	int searchSpacer = 30;

	boxRect = Rectangle(5 * getWidth() / 7 - 30, topSpacer, 2 * getWidth() / 7, getHeight() - topSpacer
			- searchSpacer);
	searchRect = Rectangle(boxRect.getX()-1, boxRect.getY() - 36, boxRect.getWidth()+2, 32);
	listBox->setBounds(boxRect);
	search->setBounds(searchRect);
}

void ListPanel::filterList(vector<String> searchStrings) {
//	for(vector<String>::iterator vit = searchStrings.begin(); vit != searchStrings.end(); ++vit) {
//		cout << vit->toUTF8() << " ";
//	}
//	cout << endl;

	filteredItems.clear();
	String name;
	deque<Eatable>& foods = getEatableList();
	if (searchStrings.empty() || searchStrings.front() == T("")) {
		copy(foods.begin(), foods.end(), inserter(filteredItems, filteredItems.begin()));
	} else {
		for (deque<Eatable>::iterator eit = foods.begin(); eit != foods.end(); ++eit) {
			name = eit->getName();
			bool containsAll = true;
			for (vector<String>::const_iterator sit = searchStrings.begin(); sit != searchStrings.end(); ++sit) {
				containsAll &= name.containsIgnoreCase(*sit);
			}
			if (containsAll) {
				filteredItems.push_back(*eit);
			}
		}
	}

//	StreamingSocket socket;
//	String url;
//	url << T("http://images.google.com/images?q=");
//	for(vector<String>::iterator sit = searchStrings.begin(); sit != searchStrings.end(); ++sit) {
//		url << *sit + T("+");
//	}
//	socket.connect(url, 80);
//	if(socket.isConnected()) {
//		cout << "Connected!"  << endl;
//	} else {
//		cout << "Not connected!" << endl;
//	}

	listBox->updateContent();
	repaint();
}
